package icu.qrcode.msg5g.chatbot.qrcodeicuSdk;

import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

public class QrcodeicuSdk {
    public String endpoint = "https://fxl.ink/portal";
    public String renderEndpoint = "https://k8s.qrcode.icu/render";

    private String appId;
    private String key;

    private String access_token;

    public String getAccessToken() {
        if (this.access_token != null) {
            return this.access_token;
        }

        String oauthApi = "/oauth/token?client_id=" + this.appId + "&client_secret=" + this.key +
                "&grant_type=client_credentials";

        String result = HttpUtil.createPost(this.endpoint + oauthApi).execute()
                .body();
        Map<String, String> retObj = (new Gson()).fromJson(result, new TypeToken<HashMap<String, String>>() {
        }.getType());

        if (retObj != null) {
            this.access_token = retObj.get("access_token");
        }

        return this.access_token;
    }

    public QrcodeicuSdk init(String endpoint,
                             String renderEndpoint,
                             String appId,
                             String key) {
        this.endpoint = endpoint;
        this.renderEndpoint = renderEndpoint;
        this.appId = appId;
        this.key = key;
        return this;
    }

    public QrcodeicuDataTableExecutor useDataTable(String dataTableId) {
        return new QrcodeicuDataTableExecutor(this, dataTableId);
    }

    public QrcodeicuPosterExecutor usePoster(String posterId, String posterCloudStorageId) {
        return new QrcodeicuPosterExecutor(this, posterId, posterCloudStorageId);
    }
}
